package com.cnsunrun.framwork.common.net;

import android.content.Context;

import com.sunrun.sunrunframwork.BaseApplication;

import cn.blesslp.pastry.MethodHandler;
import cn.blesslp.pastry.Pastry;
import cn.blesslp.pastry.PastryConfig;
import cn.blesslp.pastry.adpt.ReturnHandler;
import cn.blesslp.plugins.interceptor.CacheInterceptor;
import cn.blesslp.plugins.interceptor.LoggerInterceptor;

import static com.cnsunrun.framwork.common.net.CommonApi.ROOT_URL;

/**
 * Created by WQ on 2017/4/20.
 */

public class APIManager {

    public static void init(Context context) {
        //设置初始化配置,根路径,拦截器等
        PastryConfig.init(context)
                .addInterceptor(new LoggerInterceptor(LoggerInterceptor.LOG_TYPE.LOG_FULL))
                .addInterceptor(new CacheInterceptor(context))
                .setFlowableHandler(new ReturnHandler() {
                    @Override
                    public Object adapter(Pastry pastry, MethodHandler methodHandler) {
                        return null;
                    }
                })
                .setHost(ROOT_URL)
                .applyConfig();
    }

    public static <T> T getAPI(Object invoker,Class<T>clazz) {
        Pastry mPastry=Pastry.newInstance(invoker);
        if(mPastry.getPastryConfig()==null){
            init(BaseApplication.getInstance());//使用默认配置进行初始化
        }
        return Pastry.newInstance(invoker).create(clazz);
    }

    private APIManager() {
    }
}
